package com.hinnotek.amoeba.ui.activity.old

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.activity.viewModels
import com.google.gson.Gson
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.base.BaseBean
import com.hinnotek.amoeba.bean.old.*
import com.hinnotek.amoeba.databinding.ActivityLaborCostBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.utilities.ClickUtil
import com.lee.common.utils.SharedPreUtils
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.viewmodels.PersonViewModel
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.hinnotek.amoeba.viewmodels.SysPersonViewModel
import com.hinnotek.amoeba.widget.EditSpinnerC
import com.lee.common.network.net.ObserverState
import com.xuexiang.xutil.common.StringUtils
import dagger.hilt.android.AndroidEntryPoint
import java.util.*

@AndroidEntryPoint
class LaborCostActivity : BaseActivity<ActivityLaborCostBinding>(), View.OnClickListener {

    private val viewModel by viewModels<PublicInterfaceViewModel>()
    private val sysPersonViewModel by viewModels<SysPersonViewModel>()
    private val personViewModel by viewModels<PersonViewModel>()
    private var sysPersonListBean: MutableList<SysPersonListBean>? = null
    private var orgId = 0
    private var amibaProjectId = 0
    private var customerId = 0
    private var amibaCustomerProjectId = 0


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("人工成本")

        setContentView(R.layout.activity_labor_cost)
    }

    override fun initVew() {

        bindingView.rbLaborProduct.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                bindingView.llLaborChooseUnit.visibility = View.GONE
                bindingView.llPdProject.visibility = View.GONE
                bindingView.llPdProject.visibility = View.VISIBLE
            } else {
                bindingView.llLaborChooseUnit.visibility = View.VISIBLE
                bindingView.llPdProject.visibility = View.VISIBLE
                bindingView.llPdProject.visibility = View.GONE
            }
        }
        bindingView.rbLaborAddParticipants.setOnClickListener(this)
        bindingView.superButtonSubmit.setOnClickListener(this)
    }

    override fun setData() {
        getSysOrgAmibaList()
        getSysPersonList()
    }

    /**
     * app端添加公司人工成本录入记录接口
     */
    fun addCompanyPersonCost(
        orgId: Int,
        orgName: String,
        customerId: Int,
        customerName: String,
        amibaCustomerProjectId: Int,
        projectName: String,
        amibaProjectId: Int,
        provideProjectName: String,
        personMoney: String,
        companyPersonJson: String
    ) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        val companyPersonCostType = if (bindingView.rbLaborProduct.isChecked) 1 else 2
        val createUser = SharedPreUtils.getString("userName")

        personViewModel.addCompanyPersonCost(
            companyPersonCostType,
            orgId,
            orgName,
            customerId,
            customerName,
            amibaCustomerProjectId,
            projectName,
            amibaProjectId,
            provideProjectName,
            personMoney,
            createUser,
            companyPersonJson
        ).observe(this, object : ObserverState<BaseBean>() {
            override fun onDataChange(data: BaseBean) {
                customDialog.dismiss()
                finishActivity()
                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                customDialog.dismiss()
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }
        })
    }


    /**
     * app端获取全部阿米巴组织接口
     */
    private fun getSysOrgAmibaList() {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()
        //请求
        viewModel.getSysOrgAmibaList()
            .observe(this, object : ObserverState<MutableList<AmountAllocatedBean>>() {
                override fun onDataChange(data: MutableList<AmountAllocatedBean>) {
                    val strings = arrayOf<String?>().apply {
                        for (index in data.indices) {
                            this[index] = data.get(index).orgName
                        }
                    }
                    bindingView.escLaborChooseAmoeba.initAdapter(strings)
                    bindingView.escLaborChooseAmoeba.setOnItemClickListener { parent, view, position, id ->
                        orgId = data[position].orgId
                        bindingView.escLaborChooseProject.setText("")
                        bindingView.escLaborChooseUnit.setText("")
                        //请求
                        viewModel.getAmibaProjectListByOrgId(orgId).observe(this@LaborCostActivity,
                            object : ObserverState<MutableList<AmibaProjectListBean>>() {
                                override fun onDataChange(data: MutableList<AmibaProjectListBean>) {
                                    val arrayOfStrings = arrayOfNulls<String>(data.size).apply {
                                        for (index in data.indices) {
                                            this[index] = data[index].projectName
                                        }
                                    }
                                    bindingView.escLaborChooseProject.initAdapter(arrayOfStrings)
                                    bindingView.escLaborChooseProject.setOnItemClickListener { parent, view, position, id ->
                                        amibaProjectId = data[position].amibaProjectId
                                    }
                                    super.onDataChange(data)
                                }
                            })
                    }
                    //请求
                    viewModel.getAmibaCustomerListByOrgId(orgId).observe(this@LaborCostActivity,
                        object : ObserverState<MutableList<AmeobaCustomerListBean>>() {
                            override fun onDataChange(data: MutableList<AmeobaCustomerListBean>) {
                                val arrayOfStrings = arrayOfNulls<String>(data.size).apply {
                                    for (index in data.indices) {
                                        this[index] = data[index].customerName
                                    }
                                }
                                bindingView.escLaborChooseUnit.initAdapter(arrayOfStrings)
                                bindingView.escLaborChooseUnit.setOnItemClickListener { parent, view, position, id ->
                                    amibaProjectId = data[position].customerId
                                }
                                super.onDataChange(data)
                            }
                        })
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })
    }


    /**
     * app端下拉框获取全部员工接口
     */

    private fun getSysPersonList() {

        sysPersonViewModel.getSysPersonList()
            .observe(this, object : ObserverState<MutableList<SysPersonListBean>>() {
                override fun onDataChange(data: MutableList<SysPersonListBean>) {
                    sysPersonListBean = data
                    sysPersonListBean?.let {
                        setSysPerson(bindingView.escLaborChooseParticipants, sysPersonListBean)
                    }
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })


    }


    fun setSysPerson(editSpinnerC: EditSpinnerC, data: MutableList<SysPersonListBean>?) {
        if (data == null)
            return
        val arrString = arrayOfNulls<String>(data.size).apply {
            for (index in data.indices) {
                this[index] = data[index].personName
            }
        }
        editSpinnerC.initAdapter(arrString)
    }

    override fun onClick(v: View) {
        if (ClickUtil.isFastClick()) {
            return
        }
        when (v.id) {
            R.id.rb_labor_add_participants -> {
                val view: View = LayoutInflater.from(mContext)
                    .inflate(
                        R.layout.include_labor_cost_layout,
                        bindingView.llLaborParticipants,
                        false
                    )
                bindingView.llLaborParticipants.addView(view)
                val esc_labor_choose_participants_l: EditSpinnerC =
                    view.findViewById(R.id.esc_labor_choose_participants)
                setSysPerson(esc_labor_choose_participants_l, sysPersonListBean)
                view.findViewById<View>(R.id.tv_del)
                    .setOnClickListener { v1: View? ->
                        bindingView.llLaborParticipants.removeView(
                            view
                        )
                    }
            }
            R.id.superButton_submit -> {
                val companyPersonListBean = CompanyPersonListBean()
                var escLaborPdChooseProjectS = ""
                var escLaborChooseUnitS = ""
                var escLaborChooseProjectS = ""
                val escLaborChooseAmoebaS: String =
                    bindingView.escLaborChooseAmoeba.editText.text.toString().trim()
                if (StringUtils.isEmpty(escLaborChooseAmoebaS)) {
                    ToastUtils.show(mContext, "请选择阿米巴")
                    return
                }
                if (!bindingView.rbLaborProduct.isChecked) {
                    escLaborChooseUnitS =
                        bindingView.escLaborChooseUnit.editText.text.toString().trim()
                    if (StringUtils.isEmpty(escLaborChooseUnitS)) {
                        ToastUtils.show(mContext, "请选择签署单位")
                        return
                    }
                }
                if (bindingView.rbLaborProduct.isChecked) {
                    escLaborPdChooseProjectS =
                        bindingView.escLaborChooseProject.editText.text.toString().trim()
                    if (StringUtils.isEmpty(escLaborPdChooseProjectS)) {
                        ToastUtils.show(mContext, "请选择选择项目")
                        return
                    }
                } else {
                    escLaborChooseProjectS =
                        bindingView.escLaborChooseProject.editText.text.toString().trim()
                    if (StringUtils.isEmpty(escLaborChooseProjectS)) {
                        ToastUtils.show(mContext, "请选择选择项目")
                        return
                    }
                }
                val escLaborChooseParticipantsS: String =
                    bindingView.escLaborChooseParticipants.editText.text.toString().trim()
                if (StringUtils.isEmpty(escLaborChooseParticipantsS)) {
                    ToastUtils.show(mContext, "请选择参与人员")
                    return
                }
                companyPersonListBean.companyPersonList.add(
                    CompanyPersonListBean.Data(escLaborChooseParticipantsS)
                )
                var i = 0
                while (i < bindingView.llLaborParticipants.getChildCount()) {
                    val layout: View = bindingView.llLaborParticipants.getChildAt(i)
                    val chooseParticipantsVS: String =
                        bindingView.escLaborChooseParticipants.editText.text.toString().trim()
                    if (StringUtils.isEmpty(chooseParticipantsVS)) {
                        ToastUtils.show(mContext, "请选择参与人员")
                        return
                    }
                    companyPersonListBean.companyPersonList.add(
                        CompanyPersonListBean.Data(chooseParticipantsVS)
                    )
                    i++
                }
                val et_labor_s: String = bindingView.etLabor.text.toString().trim()
                if (StringUtils.isEmpty(et_labor_s)) {
                    ToastUtils.show(mContext, "请填写成本金额")
                    return
                }
                val companyPersonJson: String = Gson().toJson(companyPersonListBean)
                addCompanyPersonCost(
                    orgId,
                    escLaborChooseAmoebaS,
                    customerId,
                    escLaborChooseUnitS,
                    amibaCustomerProjectId,
                    escLaborChooseProjectS,
                    amibaProjectId,
                    escLaborPdChooseProjectS,
                    et_labor_s,
                    companyPersonJson
                )
            }
        }
    }
}